package com.sk.weichat.ui.message.multi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.InviteInfoBean;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.groupchat.RefuseInviteActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.util.CommonAdapter;
import com.sk.weichat.util.CommonViewHolder;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CircleImageView;
import com.sk.weichat.view.CustomPopupWindow;
import com.sk.weichat.view.MyGridView;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 群聊邀请验证页面
 */
public class InviteVerifyActivity extends BaseActivity {
//    String text, isInvite;
//    String id;
    private String mLoginUserId;
    private String friendId;
    private String packet;
//    private String mRoomId;
    private CircleImageView mInviteAvatarIv;
    private TextView mInveiteNameTv;
    private TextView mInveiteCountTv;
    private TextView mInveitReasonTv;
    private MyGridView mVerifyGridView;
    private VerifyAdapter mVerifyAdapter;
    private List<InviteInfoBean.UserListBean> mInviteList = new ArrayList<>();
//    private String mInviteUserId;

    private LinearLayout ll_dispose;
    private TextView tv_dispose_name;
    private TextView mSureTv;
    private TextView tv_refuse;

    private InviteInfoBean mInviteInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_verify);
        mLoginUserId = coreManager.getSelf().getUserId();

        if (getIntent() != null) {
            friendId = getIntent().getStringExtra("VERIFY_MESSAGE_FRIEND_ID");
            packet = getIntent().getStringExtra("VERIFY_MESSAGE_PACKET");
        }
        initAction();
        initView();
    }

    private void initAction() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.invite_detail);
    }

    private void initView() {
        mInviteAvatarIv = findViewById(R.id.invite_iv);
        mInveiteNameTv = findViewById(R.id.invite_name);
        mInveiteCountTv = findViewById(R.id.invite_number);
        mInveitReasonTv = findViewById(R.id.invite_reasonr);

        mVerifyGridView =  findViewById(R.id.verify_gd);
        mVerifyAdapter = new VerifyAdapter(this, mInviteList);
        mVerifyGridView.setAdapter(mVerifyAdapter);
        ll_dispose = findViewById(R.id.ll_dispose);
        tv_dispose_name = findViewById(R.id.tv_dispose_name);
        tv_refuse = findViewById(R.id.tv_refuse);
        mInviteAvatarIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, mInviteInfoBean.getApplicantId());
                mContext.startActivity(intent);
            }
        });
        tv_refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(InviteVerifyActivity.this, RefuseInviteActivity.class).putExtra("VERIFY_MESSAGE_PACKET",packet),1000);
            }
        });
        mSureTv = findViewById(R.id.sure_tv);
        mSureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                agreeInvite(packet);
            }
        });

        ll_dispose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(mInviteInfoBean.getOperatorName())){
                    Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, String.valueOf(mInviteInfoBean.getOperator()));
                    mContext.startActivity(intent);
                }
            }
        });
        getInviteInfo(packet);
    }


    /**
     * @author: czl
     * @description 获取邀请进群申请详情
     * @date: 2019/9/18 19:54
     */
    private void getInviteInfo(String msgId){
        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("msgId", msgId);
        HttpUtils.post().url(coreManager.getConfig().ROOM_INVITE_INFO)
                .params(params).build().execute(new BaseCallback<InviteInfoBean>(InviteInfoBean.class) {
            @Override
            public void onResponse(ObjectResult<InviteInfoBean> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode()==1){
                    mInviteInfoBean = result.getData();
                    AvatarHelper.getInstance().displayAvatar(mInviteInfoBean.getApplicantId(), mInviteAvatarIv);
                    mInveiteNameTv.setText(mInviteInfoBean.getNickname());
                    mInveitReasonTv.setText("\"" +mInviteInfoBean.getReason() + "\"");
                    mInveiteCountTv.setText(getString(R.string.tip_invite_count_place_holder,mInviteInfoBean.getUserList().size()));

                    //状态：0，待处理，1，同意；2，拒绝；3，已经过期;4，已加入
                    switch (mInviteInfoBean.getStatus()){
                        case 0:
                            ll_dispose.setVisibility(View.GONE);
                            tv_refuse.setVisibility(View.VISIBLE);
                            mSureTv.setText("同意");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,0);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_blue);
                            mSureTv.setEnabled(true);
                            break;
                        case 1:
                            ll_dispose.setVisibility(View.VISIBLE);
                            tv_dispose_name.setText(mInviteInfoBean.getOperatorName());
                            tv_refuse.setVisibility(View.GONE);
                            mSureTv.setText("该邀请已同意");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,1);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            mSureTv.setEnabled(false);
                            break;
                        case 2:
                            ll_dispose.setVisibility(View.VISIBLE);
                            tv_dispose_name.setText(mInviteInfoBean.getOperatorName());
                            tv_refuse.setVisibility(View.GONE);
                            mSureTv.setText("该邀请已拒绝");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,2);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            mSureTv.setEnabled(false);
                            break;
                        case 3:
                            ll_dispose.setVisibility(View.GONE);
                            tv_refuse.setVisibility(View.GONE);
                            mSureTv.setText("该邀请已过期");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,3);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            mSureTv.setEnabled(false);
                            break;
                        case 4:
                            ll_dispose.setVisibility(View.GONE);
                            tv_refuse.setVisibility(View.GONE);
                            if(TextUtils.isEmpty(mInviteInfoBean.getOperatorName())){
                                ll_dispose.setVisibility(View.GONE);
                            }else{
                                ll_dispose.setVisibility(View.VISIBLE);
                                tv_dispose_name.setText(mInviteInfoBean.getOperatorName());
                            }
                            mSureTv.setText("已加入");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,4);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            mSureTv.setEnabled(false);
                            break;
                        case 5:
                            ll_dispose.setVisibility(View.GONE);
                            tv_refuse.setVisibility(View.GONE);
                            mSureTv.setText("已失效");
                            GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,5);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                            mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            mSureTv.setEnabled(false);
                            break;
                    }
                    mInviteList.clear();
                    mInviteList.addAll(mInviteInfoBean.getUserList());
                    mVerifyAdapter.notifyDataSetInvalidated();
                }else {
                    ToastUtil.showToast(InviteVerifyActivity.this,result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(InviteVerifyActivity.this);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==1000){
                getInviteInfo(packet);
            }
        }
    }

    /**
     * @author: czl
     * @description 同意邀请进群
     * @date: 2019/9/18 20:54
     */
    private void agreeInvite(String msgId){
        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("msgId", msgId);
        HttpUtils.post().url(coreManager.getConfig().ROOM_JOIN_AGREE)
                .params(params).build().execute(new BaseCallback<String>(String.class) {

            @Override
            public void onResponse(ObjectResult<String> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode()==1){//同意邀请进群
                    DialogHelper.dismissProgressDialog();
                    //重新获取邀请详情
                    getInviteInfo(packet);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,1);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                    ToastUtil.showToast(InviteVerifyActivity.this,"该邀请已同意");
                    return;
                }else if(result.getResultCode()==1040321){//已过期
                    ll_dispose.setVisibility(View.GONE);
                    tv_refuse.setVisibility(View.GONE);
                    mSureTv.setText("该邀请已过期");
                    mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    mSureTv.setEnabled(false);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,3);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                }else if(result.getResultCode()==1040322){//已失效
                    ll_dispose.setVisibility(View.GONE);
                    tv_refuse.setVisibility(View.GONE);
                    mSureTv.setText("该邀请已失效");
                    mSureTv.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    mSureTv.setEnabled(false);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(),msgId,5);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                }else if (result.getResultCode()==1040324||result.getResultCode()==1040325||result.getResultCode()==1040319||result.getResultCode()==1040328){//该申请已经处理 或者 该申请已经拒绝
                    getInviteInfo(msgId);
                }
                ToastUtil.showToast(InviteVerifyActivity.this,result.getResultMsg());

            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(InviteVerifyActivity.this);
            }
        });
    }

    class VerifyAdapter extends CommonAdapter<InviteInfoBean.UserListBean> {

        VerifyAdapter(Context context, List<InviteInfoBean.UserListBean> data) {
            super(context, data);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CommonViewHolder viewHolder = CommonViewHolder.get(mContext, convertView, parent,
                    R.layout.item_verify, position);
            CircleImageView mAvatarIv = viewHolder.getView(R.id.verify_iv);
            TextView mNameTv = viewHolder.getView(R.id.verify_tv);
            AvatarHelper.getInstance().displayAvatar(data.get(position).getUserId(), mAvatarIv);

            mNameTv.setText(data.get(position).getNickname());
            ImageView img_invitation =  viewHolder.getView(R.id.img_invitation);
            if (TextUtils.isEmpty(data.get(position).getAlertMsg())){
                img_invitation.setVisibility(View.GONE);
            }else {
                img_invitation.setVisibility(View.VISIBLE);
            }
            mAvatarIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, data.get(position).getUserId());
                    mContext.startActivity(intent);
                }
            });
            img_invitation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CustomPopupWindow popupWindow = new CustomPopupWindow.Builder(InviteVerifyActivity.this)
                            .setView(R.layout.popwindow_invitation)
                            .setWidthAndHeight(ViewGroup.LayoutParams.WRAP_CONTENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT)
                            .setAnimationStyle(R.style.pop_anim)
                            .setViewOnclickListener(new CustomPopupWindow.ViewInterface() {
                                @Override
                                public void getChildView(View view, int layoutResId) {
                                    TextView tv_one = view.findViewById(R.id.tv_one);
                                    TextView tv_two = view.findViewById(R.id.tv_two);
                                    if (data.get(position).getAlertMsg().contains(";")){
                                        String[] all=data.get(position).getAlertMsg().split(";");
                                        tv_one.setText(all[0]);
                                        tv_two.setText(all[1]);
                                        tv_two.setVisibility(View.VISIBLE);
                                    }else {
                                        tv_one.setText(data.get(position).getAlertMsg());
                                        tv_two.setVisibility(View.GONE);
                                    }
                                }
                            })
                            .setOutsideTouchable(true)
                            .create();
                    popupWindow.showAsDropDown(v);
                }
            });
            return viewHolder.getConvertView();
        }
    }
}
